import pymysql
class DB:
    def __init__(self,user,password,host,databases,cursorclass):
        self.user = user
        self.password = password
        self.host = host
        self.databases = databases
        self.cursorclass = cursorclass
    def connect(self):
        self.db = pymysql.connect(user=self.user,password=self.password,host=self.host,database=self.databases
                        ,cursorclass=self.cursorclass)
        self.cursor = self.db.cursor()
    def close(self):
        self.cursor.close()
        self.db.close()
    def select_all(self,sql):
        result = 0
        try:
            self.connect()
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            self.close()
            return result
        except Exception as ec:
            self.db.rollback()
            print("数据查询失败%s"%ec)
            return result
    def select_one(self,sql):
        result = 0
        try:
            self.connect()
            self.cursor.execute(sql)
            result = self.cursor.fetchone()
            self.close()
            return result
        except Exception as ec:
            self.db.rollback()
            print("数据查询失败%s" % ec)
            return result
    def __edit(self,sql):
        result = 0
        try:
            self.connect()
            self.cursor.execute(sql)
            self.db.commit()
            result = 1
            self.close()
            return result
        except Exception as ec:
            self.db.rollback()
            print("数据更新失败%s"%ec)
            return result
    def insert(self,sql):
        return self.__edit(sql)
    def delete(self,sql):
        return self.__edit(sql)
    def update(self,sql):
        return self.__edit(sql)


if __name__ == '__main__':
    USER = 'root'
    PASSWORD = '123456'
    HOST = '8.139.7.103'
    DATABASES = 'sql8_139_7_103'
    base_url = "http://8.139.7.103:8899"
    d1 = DB(user=USER, password=PASSWORD, host=HOST, databases=DATABASES, cursorclass=pymysql.cursors.DictCursor)
    print(d1.select_one("select * from eb_user_group"))
    names = "关博文%"
    print(d1.select_all(f"select * from eb_user_group where group_name like '{names}'"))

